package com.fms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fms.dto.SysUserImageUpdateDto;
import com.fms.entity.Attendance;
import com.fms.exception.ServiceException;
import com.fms.dto.ProfileUpdateQuery;
import com.fms.dto.SysUserAdjustQuery;
import com.fms.mapper.SysDeptMapper;
import com.fms.mapper.SysUserMapper;
import com.fms.entity.SysDept;
import com.fms.entity.SysUser;
import com.fms.result.ResultData;
import com.fms.service.AttendanceService;
import com.fms.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    private final SysUserMapper sysUserMapper;

    private final SysDeptMapper sysDeptMapper;
    private final AttendanceService attendanceService;

    private final BCryptPasswordEncoder passwordEncoder;
    @Value("${fms.default.image-url:}")
    private String defaultImageURL;

    @Override
    //获取所有员工
    public List<SysUser> getAllUsers() {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        List<SysUser> sysUsers = sysUserMapper.selectList(wrapper);
        sysUsers.stream().forEach(user -> {
            if (user.getStatus()==0){
                user.setStatusName("禁用(离职)");
            }else {
                user.setStatusName("正常(在职)");
            }
            Long deptId = user.getDeptId();
            List<SysDept> dept ;
            if (deptId != null){
                dept = sysDeptMapper.getDeptById(deptId);
                if (dept.isEmpty()){
                    user.setDeptName("无职位");
                }else {
                    user.setDeptName(dept.get(0).getName());
                }
            }else {
                user.setDeptName("无职位");
            }
        });
        /*Page<SysUser> page = new Page<SysUser>();
        page.setCurrent(1);
        page.setSize(10);
        page = this.page(page,wrapper);*/
        return sysUsers;
    }

    @Override
    //获取指定员工信息
    public SysUser getUserInfo(String username) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername,username);
        return this.getOne(queryWrapper);
    }

    //管理员更新密码
    @Override
    public ResultData alterSysUserPassword(SysUser sysUser) {
        sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
        sysUserMapper.updateById(sysUser);
        return ResultData.success("密码修改成功");
    }

    @Override
    //更新员工个人信息(useless)
    public String updateProfile(ProfileUpdateQuery profileUpdateQuery) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getId,profileUpdateQuery.getId());
        SysUser one = this.getOne(queryWrapper);
        if(one == null){
            return "用户不存在";
        }
        SysUser sysUser = new SysUser();

        sysUserMapper.update(sysUser,queryWrapper);
        return "Profile details updated";
    }

    @Override
    @Transactional
    //更新员工
    public String adjustSysUser(SysUserAdjustQuery sysUserAdjustQuery) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getId,sysUserAdjustQuery.getId());
        SysUser one = this.getOne(queryWrapper);

        if(one == null){
            return "用户不存在";
        }
        String originUsername=one.getUsername();
        String username = sysUserAdjustQuery.getUsername();
        if(!originUsername.equals(username)){
            //更新任务用户名
            attendanceService.lambdaUpdate()
                    .set(username!=null, Attendance::getUsername,username)
                    .eq(Attendance::getUsername,originUsername)
                    .update();
        }
        SysUser sysUser = new SysUser();
        sysUser.setUsername(username);
        sysUser.setDeptId(sysUserAdjustQuery.getDeptId());
        sysUser.setStatus(sysUserAdjustQuery.getStatus());
        sysUserMapper.update(sysUser,queryWrapper);
        return "信息更新成功";
    }

    @Override
    //新增员工
    public String addNewSysUser(SysUser sysUser) {
        //设置默认头像信息
        sysUser.setImgUrl(defaultImageURL);
        sysUser.setStatus(1);
        sysUserMapper.insert(sysUser);
        return "员工新增成功";
    }

    @Override
    //删除员工
    public String deleteSysUser(SysUser[] sysUsers) {
        for (SysUser sysUser : sysUsers) {
            sysUserMapper.deleteById(sysUser);
        }
        return "员工删除成功";
    }

    @Override
    public String updatePassword(String username,String oldPassword, String newPassword) {
            //修改
            if(this.lambdaUpdate()
                    .set(!newPassword.isEmpty(), SysUser::getPassword, passwordEncoder.encode(newPassword))
                    .eq(SysUser::getUsername, username).update()){
                return "修改密码成功";
            }else{
                throw new ServiceException("密码修改失败,请联系管理员");
            }
    }

    @Override
    public ResultData updateImg(SysUserImageUpdateDto sysUserImageUpdateDto) {
        sysUserMapper.updateImg(sysUserImageUpdateDto.getUsername(), sysUserImageUpdateDto.getImgUrl());
        return ResultData.success("头像更新成功");
    }
}
